import { infoStore } from "./store/info";
import { createRouter, createWebHashHistory } from "vue-router";
import { SharedElementRouteGuard } from "v-shared-element";
import pages from "../pages/index.ts";
const router = createRouter({
  history: createWebHashHistory(), // hash 模式
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("/src/pages/login.vue"),
      meta: {
        title: "登录",
      },
    },
    {
      path: "/",
      name: "home",
      component: () => import("/src/pages/home.vue"),
      meta: {
        verify: "0",
        title: "5G首页",
      },
    },
    ...pages,
    {
      path: "/:pathMatch(.*)",
      redirect: {
        name: "home",
      },
    },
  ],
});
import { modal } from "vxe-table";
// 全局路由守卫
router.beforeEach((to, from, next) => {
  const info = infoStore(),
    verify = to.meta.verify;
  console.log(info.$state);
  // 自动设置标题
  if (to.meta.title) {
    const matched = to.matched;
    let title: string[] = [];
    for (let i = matched.length; i; i--) {
      const meta = matched[i - 1].meta;
      if (meta?.title) title.push(meta?.title as string);
      if (meta?.isRoot) break;
    }
    document.title = `${title
      .filter((item) => item)
      .reverse()
      .join("-")}`;
  }
  // 权限判断
  if (verify) {
    console.log("访问", to, "需要权限",info.verify);
    if (!info.verify.length && to.name !== "login") {
      next({
        name: "login",
        query: {
          to: to.fullPath,
        },
      });
    } else if (info.verify.indexOf(`${verify}`) == -1) {
      console.log(from, "访问", to, "权限不足");
      modal.message({ content: "权限不足", status: "error" });
      if (from.path === "/") {
        next({
          name: "home",
        });
      }
    } else {
      // console.log(from);
      SharedElementRouteGuard(to, from, next);
    }
  } else {
    SharedElementRouteGuard(to, from, next);
  }
});

router.afterEach((to, from) => {
  // console.log(to, from)
  // console.log("afterEach");
});

export default router;
